<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>邮箱监听管理</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
</head>
<body class="bg-gray-100 min-h-screen" x-data="mailWatcherApp()">
    <!-- 主应用界面 -->
    <div x-show="!showLoginPage" class="container mx-auto px-4 py-8">
        <!-- 顶部导航栏 -->
        <div class="mb-8 flex justify-between items-center">
            <div>
                <h1 class="text-3xl font-bold text-gray-800 mb-2">邮箱监听管理</h1>
                <p class="text-gray-600">管理您的邮箱监听配置和企业微信通知</p>
            </div>
            <button 
                @click="logout"
                class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-md transition-colors"
            >
                退出登录
            </button>
        </div>

        <!-- 企业微信配置 -->
        <div class="bg-white rounded-lg shadow-md p-6 mb-8">
            <h2 class="text-xl font-semibold text-gray-800 mb-4">企业微信群通知配置</h2>
            <div class="flex space-x-4">
                <div class="flex-1">
                    <label class="block text-sm font-medium text-gray-700 mb-1">企业微信群机器人 Webhook Key</label>
                    <input 
                        type="text" 
                        x-model="wechatForm.webhookKey"
                        class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500"
                        placeholder="输入企业微信群机器人的 webhook key"
                    >
                    <p class="text-xs text-gray-500 mt-1">获取方式：群聊 → 管理 → 群机器人 → 添加机器人 → 复制 webhook 地址中的 key 参数</p>
                </div>
                <div class="flex items-center">
                    <button 
                        @click="updateWeChatConfig"
                        :disabled="loading"
                        class="bg-green-600 hover:bg-green-700 disabled:bg-gray-400 text-white px-6 py-2 rounded-md transition-colors whitespace-nowrap"
                    >
                        <span x-show="!loading">保存配置</span>
                        <span x-show="loading">保存中...</span>
                    </button>
                </div>
            </div>
            <div x-show="wechatForm.webhookKey" class="mt-4 p-3 bg-green-50 border border-green-200 rounded-md">
                <div class="flex items-center">
                    <div class="w-3 h-3 bg-green-500 rounded-full mr-2"></div>
                    <span class="text-sm text-green-700">企业微信通知已配置</span>
                </div>
            </div>
        </div>

        <!-- 添加邮箱表单 -->
        <div class="bg-white rounded-lg shadow-md p-6 mb-8">
            <h2 class="text-xl font-semibold text-gray-800 mb-4">添加邮箱监听</h2>
            <form @submit.prevent="addWatcher" class="space-y-4">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">邮箱地址</label>
                        <input 
                            type="email" 
                            x-model="form.email"
                            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                            placeholder="example@domain.com"
                            required
                        >
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                        <input 
                            type="password" 
                            x-model="form.password"
                            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                            placeholder="邮箱密码"
                            required
                        >
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">IMAP 服务器</label>
                        <input 
                            type="text" 
                            x-model="form.host"
                            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                            placeholder="mail.nodepro8.com"
                        >
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">端口</label>
                        <input 
                            type="number" 
                            x-model="form.port"
                            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                            placeholder="993"
                        >
                    </div>
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 mb-1">回调 URL (可选)</label>
                        <input 
                            type="url" 
                            x-model="form.callback"
                            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                            placeholder="https://your-callback-url.com/webhook"
                        >
                        <div class="mt-1 text-xs text-gray-500">
                            <p>• 如果配置回调 URL：邮件数据会发送到回调地址，企业微信通知由回调处理</p>
                            <p>• 如果不配置回调：邮件通知将不会处理</p>
                        </div>
                    </div>
                    <div class="flex items-center">
                        <input 
                            type="checkbox" 
                            x-model="form.tls"
                            id="tls"
                            class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                        >
                        <label for="tls" class="ml-2 block text-sm text-gray-700">使用 TLS</label>
                    </div>
                </div>

                <!-- 自动回复配置 -->
                <div class="border-t pt-4">
                    <h3 class="text-lg font-medium text-gray-800 mb-3">自动回复配置</h3>
                    <div class="space-y-4">
                        <div class="flex items-center">
                            <input 
                                type="checkbox" 
                                x-model="form.autoReply.enabled"
                                id="autoReplyEnabled"
                                class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                            >
                            <label for="autoReplyEnabled" class="ml-2 block text-sm text-gray-700">启用自动回复</label>
                        </div>

                        <div x-show="form.autoReply.enabled" class="space-y-3">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">主题前缀</label>
                                <input 
                                    type="text" 
                                    x-model="form.autoReply.subjectPrefix"
                                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                    placeholder="Re: "
                                >
                            </div>

                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">回复内容</label>
                                <textarea 
                                    x-model="form.autoReply.textContent"
                                    rows="3"
                                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                    placeholder="感谢您的邮件，我已收到并会尽快回复。"
                                ></textarea>
                            </div>

                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">HTML 内容（可选）</label>
                                <textarea 
                                    x-model="form.autoReply.htmlContent"
                                    rows="2"
                                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                    placeholder="<p>感谢您的邮件，我已收到并会尽快回复。</p>"
                                ></textarea>
                                <p class="text-xs text-gray-500 mt-1">如果不填写，将使用纯文本内容</p>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="flex justify-end">
                    <button 
                        type="submit"
                        :disabled="loading"
                        class="bg-blue-600 hover:bg-blue-700 disabled:bg-gray-400 text-white px-6 py-2 rounded-md transition-colors"
                    >
                        <span x-show="!loading">添加监听</span>
                        <span x-show="loading">添加中...</span>
                    </button>
                </div>
            </form>
        </div>

        <!-- 当前监听的邮箱列表 -->
        <div class="bg-white rounded-lg shadow-md p-6">
            <h2 class="text-xl font-semibold text-gray-800 mb-4">当前监听邮箱</h2>
            
            <!-- 加载状态 -->
            <div x-show="loadingWatchers" class="text-center py-8">
                <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
                <p class="mt-2 text-gray-600">加载中...</p>
            </div>

            <!-- 邮箱列表 -->
            <div x-show="!loadingWatchers" class="space-y-4">
                <template x-for="watcher in watchers" :key="watcher.email">
                    <div class="border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow">
                        <div class="flex items-center justify-between">
                            <div class="flex-1">
                                <div class="flex items-center space-x-3">
                                    <div :class="getStatusColor(watcher)" class="w-3 h-3 rounded-full"></div>
                                    <h3 class="text-lg font-medium text-gray-800" x-text="watcher.email"></h3>
                                    <span x-show="watcher.status === 'active'" :class="getStatusBadgeClass(watcher)" class="text-xs px-2 py-1 rounded-full" x-text="getStatusText(watcher)"></span>
                                    <span x-show="watcher.status === 'inactive'" class="text-xs bg-gray-100 text-gray-800 px-2 py-1 rounded-full">已保存</span>
                                    <span class="text-xs bg-green-100 text-green-800 px-2 py-1 rounded-full">企业微信通知</span>
                                </div>
                                <div class="mt-2 text-sm text-gray-600">
                                    <p><span class="font-medium">服务器:</span> <span x-text="watcher.host || 'mail.nodepro8.com'"></span></p>
                                    <p><span class="font-medium">端口:</span> <span x-text="watcher.port || '993'"></span></p>
                                    <p x-show="watcher.callback"><span class="font-medium">回调:</span> <span x-text="watcher.callback"></span></p>
                                    <p x-show="!watcher.callback" class="text-gray-400"><span class="font-medium">回调:</span> 仅企业微信通知</p>
                                    <p x-show="watcher.status === 'active' && watcher.connectionStatus" class="mt-1">
                                        <span class="font-medium">状态:</span> 
                                        <span :class="getStatusTextColor(watcher)" x-text="watcher.connectionStatus.message"></span>
                                        <span x-show="watcher.connectionStatus.lastUpdate" class="text-xs text-gray-400 ml-2" x-text="formatTime(watcher.connectionStatus.lastUpdate)"></span>
                                    </p>
                                </div>
                            </div>
                            <div class="flex space-x-2">
                                <template x-if="watcher.status === 'inactive'">
                                    <button 
                                        @click="showRestartModalDialog(watcher)"
                                        class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md text-sm transition-colors"
                                    >
                                        重启
                                    </button>
                                </template>
                                <template x-if="watcher.status === 'active'">
                                    <button 
                                        @click="editWatcher(watcher)"
                                        class="bg-yellow-500 hover:bg-yellow-600 text-white px-4 py-2 rounded-md text-sm transition-colors"
                                    >
                                        编辑
                                    </button>
                                </template>
                                <button 
                                    @click="removeWatcher(watcher.email)"
                                    :disabled="loading"
                                    class="bg-red-600 hover:bg-red-700 disabled:bg-gray-400 text-white px-4 py-2 rounded-md text-sm transition-colors"
                                >
                                    删除
                                </button>
                            </div>
                        </div>
                    </div>
                </template>

                <div x-show="watchers.length === 0" class="text-center py-8 text-gray-500">
                    <p>暂无监听邮箱</p>
                </div>
            </div>
        </div>

        <!-- 重启监听器模态框 -->
        <div x-show="showRestartModalFlag" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50" @click.away="showRestartModalFlag = false">
            <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
                <div class="mt-3">
                    <h3 class="text-lg font-medium text-gray-900 mb-4">重启邮箱监听</h3>
                    <form @submit.prevent="restartWatcher" class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">邮箱地址</label>
                            <input 
                                type="email" 
                                x-model="restartForm.email"
                                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                disabled
                            >
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                            <input 
                                type="password" 
                                x-model="restartForm.password"
                                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                placeholder="请输入邮箱密码"
                                required
                            >
                            <p class="text-xs text-gray-500 mt-1">需要重新输入密码以重启监听（密码不会被保存）</p>
                        </div>
                        <div class="flex justify-end space-x-2">
                            <button 
                                type="button"
                                @click="showRestartModalFlag = false"
                                class="bg-gray-300 hover:bg-gray-400 text-gray-800 px-4 py-2 rounded-md transition-colors"
                            >
                                取消
                            </button>
                            <button 
                                type="submit"
                                :disabled="loading"
                                class="bg-blue-600 hover:bg-blue-700 disabled:bg-gray-400 text-white px-4 py-2 rounded-md transition-colors"
                            >
                                重启监听
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- 编辑模态框 -->
        <div x-show="showEditModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50" @click.away="showEditModal = false">
            <div class="relative top-10 mx-auto p-5 border w-full max-w-2xl shadow-lg rounded-md bg-white">
                <div class="mt-3">
                    <h3 class="text-lg font-medium text-gray-900 mb-4">编辑邮箱监听</h3>
                    <form @submit.prevent="updateWatcher" class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">邮箱地址</label>
                            <input 
                                type="email" 
                                x-model="editForm.email"
                                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                disabled
                            >
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">回调 URL</label>
                            <input 
                                type="url" 
                                x-model="editForm.callback"
                                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                placeholder="留空则仅发送企业微信通知"
                            >
                        </div>

                        <!-- 自动回复配置 -->
                        <div class="border-t pt-4">
                            <h4 class="text-md font-medium text-gray-800 mb-3">自动回复配置</h4>
                            <div class="space-y-3">
                                <div class="flex items-center">
                                    <input 
                                        type="checkbox" 
                                        x-model="editForm.autoReply.enabled"
                                        id="editAutoReplyEnabled"
                                        class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                                    >
                                    <label for="editAutoReplyEnabled" class="ml-2 block text-sm text-gray-700">启用自动回复</label>
                                </div>

                                <div x-show="editForm.autoReply.enabled" class="space-y-3">
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-1">主题前缀</label>
                                        <input 
                                            type="text" 
                                            x-model="editForm.autoReply.subjectPrefix"
                                            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                            placeholder="Re: "
                                        >
                                    </div>

                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-1">回复内容</label>
                                        <textarea 
                                            x-model="editForm.autoReply.textContent"
                                            rows="3"
                                            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                            placeholder="感谢您的邮件，我已收到并会尽快回复。"
                                        ></textarea>
                                    </div>

                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-1">HTML 内容（可选）</label>
                                        <textarea 
                                            x-model="editForm.autoReply.htmlContent"
                                            rows="2"
                                            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                            placeholder="<p>感谢您的邮件，我已收到并会尽快回复。</p>"
                                        ></textarea>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="flex justify-end space-x-2">
                            <button 
                                type="button"
                                @click="showEditModal = false"
                                class="bg-gray-300 hover:bg-gray-400 text-gray-800 px-4 py-2 rounded-md transition-colors"
                            >
                                取消
                            </button>
                            <button 
                                type="submit"
                                :disabled="loading"
                                class="bg-blue-600 hover:bg-blue-700 disabled:bg-gray-400 text-white px-4 py-2 rounded-md transition-colors"
                            >
                                更新
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- 登录页面 -->
    <div x-show="showLoginPage" class="min-h-screen flex items-center justify-center">
        <div class="bg-white p-8 rounded-lg shadow-md w-96">
            <div class="text-center mb-6">
                <h1 class="text-2xl font-bold text-gray-800">邮箱监听管理</h1>
                <p class="text-gray-600 mt-2">请输入密码访问管理界面</p>
            </div>
            
            <form @submit.prevent="login" class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">管理密码</label>
                    <input 
                        type="password" 
                        x-model="loginPassword"
                        class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                        placeholder="请输入管理密码"
                        required
                    >
                </div>
                <button 
                    type="submit"
                    :disabled="loginLoading"
                    class="w-full bg-blue-600 hover:bg-blue-700 disabled:bg-gray-400 text-white py-2 rounded-md transition-colors"
                >
                    <span x-show="!loginLoading">登录</span>
                    <span x-show="loginLoading">登录中...</span>
                </button>
                <div x-show="loginError" class="text-red-600 text-sm text-center" x-text="loginError"></div>
            </form>
        </div>
    </div>

    <!-- 消息提示 -->
    <div x-show="message" 
         x-transition:enter="transition ease-out duration-300"
         x-transition:enter-start="opacity-0 transform translate-y-2"
         x-transition:enter-end="opacity-100 transform translate-y-0"
         x-transition:leave="transition ease-in duration-200"
         x-transition:leave-start="opacity-100 transform translate-y-0"
         x-transition:leave-end="opacity-0 transform translate-y-2"
         class="fixed top-4 right-4 z-50">
        <div :class="messageType === 'success' ? 'bg-green-500' : 'bg-red-500'" 
             class="text-white px-6 py-3 rounded-lg shadow-lg">
            <p x-text="message"></p>
        </div>
    </div>

    <script>
        function mailWatcherApp() {
            return {
                // 认证相关
                showLoginPage: true,
                loginPassword: '',
                loginLoading: false,
                loginError: '',
                sessionId: localStorage.getItem('sessionId') || '',
                
                // 应用状态
                watchers: [],
                loading: false,
                loadingWatchers: true,
                message: '',
                messageType: 'success',
                showEditModal: false,
                showRestartModalFlag: false,
                
                // 表单数据
                form: {
                    email: '',
                    password: '',
                    host: 'mail.nodepro8.com',
                    port: 143,
                    callback: 'http://150.5.163.98:3001/api/mail/callback',
                    tls: false,
                    autoReply: {
                        enabled: false,
                        subjectPrefix: 'Re: ',
                        textContent: '感谢您的邮件，我已收到并会尽快回复。',
                        htmlContent: '<p>感谢您的邮件，我已收到并会尽快回复。</p>'
                    }
                },
                editForm: {
                    email: '',
                    callback: '',
                    autoReply: {
                        enabled: false,
                        subjectPrefix: 'Re: ',
                        textContent: '感谢您的邮件，我已收到并会尽快回复。',
                        htmlContent: '<p>感谢您的邮件，我已收到并会尽快回复。</p>'
                    }
                },
                restartForm: {
                    email: '',
                    password: ''
                },
                wechatForm: {
                    webhookKey: ''
                },

                async init() {
                    console.log('App initializing...');
                    // 检查是否已有有效session
                    if (this.sessionId) {
                        console.log('Found existing session, verifying...');
                        const isValid = await this.verifySession();
                        if (isValid) {
                            console.log('Session valid, loading app data...');
                            this.showLoginPage = false;
                            await this.loadWatchers();
                            await this.loadWeChatConfig();
                        } else {
                            console.log('Session invalid, clearing...');
                            this.sessionId = '';
                            localStorage.removeItem('sessionId');
                            this.showLoginPage = true;
                        }
                    } else {
                        console.log('No session found, showing login page');
                        this.showLoginPage = true;
                    }
                },

                // 发送API请求的通用方法
                async apiRequest(url, options = {}) {
                    const headers = {
                        'Content-Type': 'application/json',
                        ...options.headers
                    };
                    
                    if (this.sessionId) {
                        headers['x-session-id'] = this.sessionId;
                    }
                    
                    const response = await fetch(url, {
                        ...options,
                        headers
                    });
                    
                    // 如果返回401，需要重新登录
                    if (response.status === 401) {
                        this.sessionId = '';
                        localStorage.removeItem('sessionId');
                        this.showLoginPage = true;
                        throw new Error('需要重新登录');
                    }
                    
                    return response;
                },

                // 验证session
                async verifySession() {
                    try {
                        const response = await this.apiRequest('/api/verify');
                        return response.ok;
                    } catch (error) {
                        return false;
                    }
                },

                // 登录
                async login() {
                    this.loginLoading = true;
                    this.loginError = '';
                    
                    try {
                        const response = await fetch('/api/login', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({ password: this.loginPassword })
                        });
                        
                        const data = await response.json();
                        
                        if (response.ok) {
                            this.sessionId = data.sessionId;
                            localStorage.setItem('sessionId', this.sessionId);
                            this.showLoginPage = false;
                            this.loginPassword = '';
                            await this.loadWatchers();
                            await this.loadWeChatConfig();
                            this.showMessage('登录成功', 'success');
                        } else {
                            this.loginError = data.message || '登录失败';
                        }
                    } catch (error) {
                        this.loginError = '网络错误，请重试';
                    } finally {
                        this.loginLoading = false;
                    }
                },

                // 登出
                async logout() {
                    try {
                        await this.apiRequest('/api/logout', { method: 'POST' });
                    } catch (error) {
                        // 忽略登出错误
                    } finally {
                        this.sessionId = '';
                        localStorage.removeItem('sessionId');
                        this.showLoginPage = true;
                        this.watchers = [];
                        this.wechatForm.webhookKey = '';
                        this.showMessage('已退出登录', 'success');
                    }
                },

                async loadWatchers() {
                    this.loadingWatchers = true;
                    try {
                        const response = await this.apiRequest('/api/watchers');
                        const data = await response.json();
                        this.watchers = data.watchers || [];
                        if (data.wechatConfig) {
                            this.wechatForm.webhookKey = data.wechatConfig.webhookKey || '';
                        }
                    } catch (error) {
                        this.showMessage('加载监听列表失败', 'error');
                    } finally {
                        this.loadingWatchers = false;
                    }
                },

                async loadWeChatConfig() {
                    try {
                        const response = await this.apiRequest('/api/wechat/config');
                        const data = await response.json();
                        this.wechatForm.webhookKey = data.webhookKey || '';
                    } catch (error) {
                        console.error('Failed to load WeChat config:', error);
                    }
                },

                async updateWeChatConfig() {
                    if (!this.wechatForm.webhookKey.trim()) {
                        this.showMessage('请输入企业微信 Webhook Key', 'error');
                        return;
                    }

                    this.loading = true;
                    try {
                        const response = await this.apiRequest('/api/wechat/config', {
                            method: 'POST',
                            body: JSON.stringify(this.wechatForm)
                        });

                        const data = await response.json();
                        
                        if (response.ok) {
                            this.showMessage('企业微信配置保存成功', 'success');
                        } else {
                            this.showMessage(data.error || '配置保存失败', 'error');
                        }
                    } catch (error) {
                        this.showMessage('网络错误', 'error');
                    } finally {
                        this.loading = false;
                    }
                },

                showRestartModalDialog(watcher) {
                    this.restartForm = {
                        email: watcher.email,
                        password: ''
                    };
                    this.showRestartModalFlag = true;
                },

                async restartWatcher() {
                    this.loading = true;
                    try {
                        const response = await this.apiRequest('/restart', {
                            method: 'POST',
                            body: JSON.stringify(this.restartForm)
                        });

                        const data = await response.json();
                        
                        if (response.ok) {
                            this.showMessage('邮箱监听重启成功', 'success');
                            this.showRestartModalFlag = false;
                            this.restartForm = { email: '', password: '' };
                            await this.loadWatchers();
                        } else {
                            this.showMessage(data.error || '重启失败', 'error');
                        }
                    } catch (error) {
                        this.showMessage('网络错误', 'error');
                    } finally {
                        this.loading = false;
                    }
                },

                async addWatcher() {
                    this.loading = true;
                    try {
                        const response = await this.apiRequest('/add', {
                            method: 'POST',
                            body: JSON.stringify(this.form)
                        });

                        const data = await response.json();
                        
                        if (response.ok) {
                            this.showMessage('邮箱监听添加成功', 'success');
                            this.resetForm();
                            await this.loadWatchers();
                        } else {
                            this.showMessage(data.error || '添加失败', 'error');
                        }
                    } catch (error) {
                        this.showMessage('网络错误', 'error');
                    } finally {
                        this.loading = false;
                    }
                },

                async removeWatcher(email) {
                    if (!confirm(`确定要删除 ${email} 的监听吗？\n\n注意：这将删除保存的配置，如需重新监听需要重新添加。`)) {
                        return;
                    }

                    this.loading = true;
                    try {
                        const response = await this.apiRequest('/remove', {
                            method: 'POST',
                            body: JSON.stringify({ email })
                        });

                        const data = await response.json();
                        
                        if (response.ok) {
                            this.showMessage('邮箱监听删除成功', 'success');
                            await this.loadWatchers();
                        } else {
                            this.showMessage(data.error || '删除失败', 'error');
                        }
                    } catch (error) {
                        this.showMessage('网络错误', 'error');
                    } finally {
                        this.loading = false;
                    }
                },

                editWatcher(watcher) {
                    this.editForm = {
                        email: watcher.email,
                        callback: watcher.callback || '',
                        autoReply: {
                            enabled: watcher.autoReply?.enabled || false,
                            subjectPrefix: watcher.autoReply?.subjectPrefix || 'Re: ',
                            textContent: watcher.autoReply?.textContent || '感谢您的邮件，我已收到并会尽快回复。',
                            htmlContent: watcher.autoReply?.htmlContent || '<p>感谢您的邮件，我已收到并会尽快回复。</p>'
                        }
                    };
                    this.showEditModal = true;
                },

                async updateWatcher() {
                    this.loading = true;
                    try {
                        const response = await this.apiRequest('/update', {
                            method: 'POST',
                            body: JSON.stringify(this.editForm)
                        });

                        const data = await response.json();
                        
                        if (response.ok) {
                            this.showMessage('邮箱监听更新成功', 'success');
                            this.showEditModal = false;
                            await this.loadWatchers();
                        } else {
                            this.showMessage(data.error || '更新失败', 'error');
                        }
                    } catch (error) {
                        this.showMessage('网络错误', 'error');
                    } finally {
                        this.loading = false;
                    }
                },

                resetForm() {
                    this.form = {
                        email: '',
                        password: '',
                        host: 'mail.nodepro8.com',
                        port: 993,
                        callback: '',
                        tls: true,
                        autoReply: {
                            enabled: false,
                            subjectPrefix: 'Re: ',
                            textContent: '感谢您的邮件，我已收到并会尽快回复。',
                            htmlContent: '<p>感谢您的邮件，我已收到并会尽快回复。</p>'
                        }
                    };
                },

                showMessage(text, type = 'success') {
                    this.message = text;
                    this.messageType = type;
                    setTimeout(() => {
                        this.message = '';
                    }, 3000);
                },

                // 辅助函数：获取状态颜色
                getStatusColor(watcher) {
                    if (watcher.status === 'inactive') {
                        return 'bg-gray-400';
                    }
                    
                    const connStatus = watcher.connectionStatus?.status;
                    switch (connStatus) {
                        case 'connected':
                            return 'bg-green-500';
                        case 'connecting':
                            return 'bg-yellow-500';
                        case 'error':
                            return 'bg-red-500';
                        case 'disconnected':
                            return 'bg-orange-500';
                        default:
                            return 'bg-gray-400';
                    }
                },

                // 辅助函数：获取状态文本
                getStatusText(watcher) {
                    if (watcher.status === 'inactive') {
                        return '已保存';
                    }
                    
                    const connStatus = watcher.connectionStatus?.status;
                    switch (connStatus) {
                        case 'connected':
                            return '已连接';
                        case 'connecting':
                            return '连接中';
                        case 'error':
                            return '错误';
                        case 'disconnected':
                            return '已断开';
                        default:
                            return '未知';
                    }
                },

                // 辅助函数：获取状态文本颜色
                getStatusTextColor(watcher) {
                    if (watcher.status === 'inactive') {
                        return 'text-gray-600';
                    }
                    
                    const connStatus = watcher.connectionStatus?.status;
                    switch (connStatus) {
                        case 'connected':
                            return 'text-green-700';
                        case 'connecting':
                            return 'text-yellow-700';
                        case 'error':
                            return 'text-red-700';
                        case 'disconnected':
                            return 'text-orange-700';
                        default:
                            return 'text-gray-600';
                    }
                },

                // 辅助函数：获取状态徽章类
                getStatusBadgeClass(watcher) {
                    if (watcher.status === 'inactive') {
                        return 'bg-gray-100 text-gray-800';
                    }
                    
                    const connStatus = watcher.connectionStatus?.status;
                    switch (connStatus) {
                        case 'connected':
                            return 'bg-green-100 text-green-800';
                        case 'connecting':
                            return 'bg-yellow-100 text-yellow-800';
                        case 'error':
                            return 'bg-red-100 text-red-800';
                        case 'disconnected':
                            return 'bg-orange-100 text-orange-800';
                        default:
                            return 'bg-gray-100 text-gray-800';
                    }
                },

                // 辅助函数：格式化时间
                formatTime(timestamp) {
                    if (!timestamp) return '';
                    const date = new Date(timestamp);
                    const now = new Date();
                    const diffMinutes = (now - date) / (1000 * 60);

                    if (diffMinutes < 1) {
                        return '刚刚';
                    } else if (diffMinutes < 60) {
                        return `${Math.floor(diffMinutes)}分钟前`;
                    } else if (diffMinutes < 1440) { // 24小时
                        return `${Math.floor(diffMinutes / 60)}小时前`;
                    } else {
                        return `${date.getMonth() + 1}/${date.getDate()} ${date.getHours()}:${date.getMinutes()}`;
                    }
                }
            }
        }
    </script>
</body>
</html> 